const http = require('http');
const port = 3000;
const url = require('url');
const path = require('path');
const fs = require('fs');
const Koa = require('koa');
var staticServe = require('./static');
const cors = require('koa2-cors');

const Router = require('koa-router');
var router = new Router();
const {historyApiFallback } = require('koa2-connect-history-api-fallback');
// const staticServe = requi/re('koa-static');

//nodejs api 实现 server
function App() {
    let server = http.createServer((req, res) => {
        console.log(req.url);
        const urlObj = url.parse(req.url);
        console.log('urlObj:');
        console.log(urlObj);
        let { pathname } = urlObj;
        if (pathname.startsWith('/api')) {
            if (pathname == '/api/users') {
                let { method } = req;
                console.log(`method: ${method}`);
                if (method === 'GET') {
                    let resData = [
                        {
                            id: 1,
                            name: '小明',
                            age: 18
                        },
                        {
                            id: 2,
                            name: '小红',
                            age: 19
                        }
                    ];
                    res.setHeader('Content-Type', 'application/json');
                    res.end(JSON.stringify(resData));
                    return;
                } else if (method == 'POST') {
                    console.log('进来 post');
                    let postData = '';
                    let body = []
                    req.on('data', chunk => {
                        console.log('获取数据');
                        console.log(chunk);
                        // postData = postData + chunk;
                        body.push(chunk);  //二进制数据
                    });

                    req.on('end', () => {
                        console.log('获取数据结束');
                        console.log(postData);
                        let chunks = Buffer.concat(body);
                        fs.appendFile(path.join(__dirname, 'db.txt'), chunks, () => {
                            res.end(chunks);
                        });
                    });
                }
            }
        } else {
            //静态文件，根据不同文件类型设置不同 Content-Type
            let extName = path.extname(pathname);
            console.log(`extName: ${extName}`);
            if (extName === '.html') {
                console.log('__dirname:' + __dirname);
                let p = path.join(__dirname, pathname);
                console.log(`pathname: ${p}`);
                fs.readFile(p, (err, data) => {
                    if (err) {
                        console.log('出错了');
                        throw err;
                    }
                    res.setHeader('Content-Type', 'text/html');
                    res.write(data);
                    res.end();
                })
            }
            // else{
            //     res.statusCode = 404;
            //     res.write('Not Found');
            //     res.end();
            // }
        }
        // res.statusCode = 200;
        // res.setHeader('Content-Type','text/plain');
        // res.end('Hello World');
    });

    server.listen(port, () => {
        console.log(`Server is running on http://127.0.0.1:${port}`);
    });
}

// App();

// console.log('path.parse:');
// console.log(path.parse(path.resolve(__dirname)));

function koaServer() {
    const app = new Koa();
    console.log('app.env:');
    console.log(app.env);
    console.log('app.keys:');
    console.log(app.keys);

    // app.use(cors({
        
    //     maxAge: 5,
    //     credentials: true, 
        
        
    // }));
    app.use(historyApiFallback({
        whiteList: ['/api']
    }));

    app.use(cors({
        origin: function(ctx){
            return '*';
        },
        allowHeaders: ['Content-Type', 'Accept'],
        allowMethods: ['POST','DELETE'],
        credentials: false
    }));

    router.get('/test', async (ctx, next)=>{
        ctx.status = 200;
        ctx.body = {
            code: 1,
            result: {
                name: 'katy'
            }
        }
    });


    app.use(router.routes()).use(router.allowedMethods());

    app.use(async (ctx, next) => {
        // console.log('ctx.path: '+ctx.path);
        // console.log(path.parse((ctx.path)));
        // console.log('ctx.headers:');
        // console.log(ctx.headers);
        // console.log(ctx.header);
        console.log('ctx.accepts:');
        // console.log(ctx.accepts());
        // console.log(ctx.get('accept'))
        console.log('url 修改前：');
        console.log('url: '+ctx.url+' ,path:  '+ctx.path);
        // ctx.url = '/api/test';
        console.log('url 修改后：');
        console.log('url: '+ctx.url+' ,path:  '+ctx.path);
        await next();
    });

    // app.use((ctx, next)=>{
    //     console.log('经过 historyApiFallback 中间件前：');
    //     console.log(`path: ${ctx.path}, url: ${ctx.url}`);
    //     // console.log(ctx.req);
    //     next();
    // })

    // app.use((ctx, next)=>{
    //     console.log('经过 historyApiFallback 中间件后，staticServe 中间件前：');
    //     console.log(`path: ${ctx.path}, url: ${ctx.url}`);
    //     // console.log(ctx.req);
    //     next();
    // })

    app.use(async (ctx, next)=>{
        console.log('另一个中间件输出：');
        console.log('url: '+ctx.url+' ,path:  '+ctx.path);
        await next();
    })

    //可以指定首页到底是哪个
    app.use(staticServe('./views', {
        index: 'tmp.html'
    }));

    app.listen(port, () => {
        console.log(`Server is running on http://127.0.0.1:${port}`)
    });
}

koaServer();